import {useEffect, createRef} from 'react';
import {
  NavigationContainerRef,
  NavigationState,
} from '@react-navigation/native';
import {Dimensions} from 'react-native';
const {width: viewportWidth, height: viewportHeight} = Dimensions.get('window'); // 获取到屏幕宽度与高度

function wp(percentage: number) {
  const value = (percentage * viewportWidth) / 100;
  return Math.round(value);
}

function hp(percentage: number) {
  const value = (percentage * viewportHeight) / 100;
  return Math.round(value);
}

function getActiveRouteName(state: NavigationState) {
  let route;
  route = state.routes[state.index];
  while (route.state && route.state.index) {
    route = route.state.routes[route.state.index];
  }
  return route.name;
}
/**
 * 等价于class组件中的componentDidMount
 * @param callBack 回调函数
 */
const useDidMount = (callBack: () => void) => {
  useEffect(() => {
    if (typeof callBack === 'function') {
      callBack();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
};

function getTimeString(seconds: number) {
  const m = parseInt((seconds % (60 * 60)) / 60 + '', 10);
  const s = parseInt((seconds % 60) + '', 10);

  return (m < 10 ? '0' + m : m) + ':' + (s < 10 ? '0' + s : s);
}

const navigationRef = createRef<NavigationContainerRef>();

const navigate = (name: string, params?: any) => {
  navigationRef?.current?.navigate(name, params);
};
const goBack = () => {
  navigationRef.current?.goBack();
};

export {
  viewportWidth,
  viewportHeight,
  wp,
  hp,
  getActiveRouteName,
  useDidMount,
  getTimeString,
  navigationRef,
  navigate,
  goBack,
};
